//
//  AppDelegate.m
//  xingfugangwan
//
//  Created by rainday on 14/12/15.
//  Copyright (c) 2014年 rainday. All rights reserved.
//

#import "AppDelegate.h"
#import "LogViewController.h"
#import <AFNetworking.h>
#import <RACEXTScope.h>
#import "NetIP.h"

@interface AppDelegate () <UISplitViewControllerDelegate>
@property (nonatomic,readonly) UISplitViewController *rootViewController;
@property (nonatomic,readonly) LogViewController *logViewController;


@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
    _rootViewController = splitViewController;
    
    _logViewController = [[LogViewController alloc] initWithNibName:@"LogViewController" bundle:nil];
    
    UINavigationController *navigationController = [splitViewController.viewControllers lastObject];
    
    
    
    
    
    
    // displayViewCongtroller is availd in ios8
    if ([splitViewController respondsToSelector:@selector(displayModeButtonItem)]) {
        navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem;
    }else{
        
    
    }
    
    
    
    
    splitViewController.delegate = self;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hasLogin:) name:@"login" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hasLogout:) name:@"logout" object:nil];
    
    
    NSUserDefaults *userdefaults = [NSUserDefaults standardUserDefaults];
    
    
    id token = [userdefaults objectForKey:@"token"];
    
    if (token) {
        
        
        
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        
        [manager.requestSerializer setValue:[NSString stringWithFormat:@"Token %@",token] forHTTPHeaderField:@"Authorization"];
        [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [manager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        
        
        
        
        [manager POST:[[NetIP shareNetAddress] getAuthURLString] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            
           
                            NSLog(@"%@",responseObject);
            
            if ([responseObject[@"state"] isEqualToString:@"success"]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"login" object:nil];

            }else{
                [[NSNotificationCenter defaultCenter] postNotificationName:@"logout" object:nil];

            }
            
           
            
            
            
            
            
            
            
            
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Error: %@", error);
        }];
        

        return YES;
        
    
       
    }
    
    
    self.window.rootViewController = _logViewController;

    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    
    NSUserDefaults *userdefaults = [NSUserDefaults standardUserDefaults];
    
    
    id token = [userdefaults objectForKey:@"token"];
    
    if (token) {
        
        
        
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        
        [manager.requestSerializer setValue:[NSString stringWithFormat:@"Token %@",token] forHTTPHeaderField:@"Authorization"];
        [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [manager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        
        
        
        
        [manager POST:[[NetIP shareNetAddress] getAuthURLString] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            
            
            NSLog(@"%@",responseObject);
            
            if ([responseObject[@"state"] isEqualToString:@"success"]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"login" object:nil];
                
            }else{
                [[NSNotificationCenter defaultCenter] postNotificationName:@"logout" object:nil];
                
            }
            
            
            
            
            
            
            
            
            
            
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Error: %@", error);
        }];
        return;
        
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"logout" object:nil];
    
    
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    //此时判断用户是否登录
    
    
    
    
    
    
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark - Split view

- (BOOL)splitViewController:(UISplitViewController *)splitViewController collapseSecondaryViewController:(UIViewController *)secondaryViewController ontoPrimaryViewController:(UIViewController *)primaryViewController {
   
    return YES;
}

- (void)splitViewController:(UISplitViewController *)svc willHideViewController:(UIViewController *)aViewController withBarButtonItem:(UIBarButtonItem *)barButtonItem forPopoverController:(UIPopoverController *)pc
{
    UINavigationController* slaveNavigationViewController = svc.viewControllers[1];
    UIViewController*       slaveViewController = slaveNavigationViewController.viewControllers[0];
    
    [barButtonItem setImage:[[UIImage imageNamed:@"个人中心icon"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    slaveViewController.navigationItem.leftBarButtonItem = barButtonItem;
}

- (void)splitViewController:(UISplitViewController *)svc willShowViewController:(UIViewController *)aViewController invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem
{
    UINavigationController* slaveNavigationViewController = svc.viewControllers[1];
    UIViewController*       slaveViewController = slaveNavigationViewController.viewControllers[0];
    slaveViewController.navigationItem.leftBarButtonItem = nil;
}

- (void)hasLogin:(NSNotification *)aNotification{
    self.window.rootViewController = _rootViewController;

}
- (void)hasLogout:(NSNotification *)aNotification{
    self.window.rootViewController = _logViewController;
    
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    
}
@end
